package cn.bone.sentinel.util;

import cn.bone.sentinel.bean.Person;
import cn.bone.sentinel.exception.ParamTypeException;
import jodd.bean.BeanUtil;
import jodd.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ParamUtil {

    public static <T> T getParam(Class<T> clazz, HttpServletRequest request){
        T o = null;
        try {
            o = clazz.getConstructor().newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        Field[] fields = clazz.getDeclaredFields();
        try{
            for(Field field : fields){
                String parameter = request.getParameter(field.getName());
                if(StringUtil.isEmpty(parameter)){
                    continue;
                }
                BeanUtil.pojo.setProperty(o,field.getName(),parameter);
            }
        }catch (Exception e){
            throw new ParamTypeException("参数类型错误");
        }
        return o;
    }
}
